<?php

namespace App\Http\Controllers\Home;

use App\Api\Helpers\ApiResponse;
use App\Events\UserRegistered;
use App\Events\SendNoticeToOne;
use App\Http\Controllers\Controller;
use App\Models\Sms;
use App\Models\User;
use App\Models\Wallet;
use App\Models\PowerLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;

class RegisterController extends Controller
{
    use ApiResponse;
    //注册
    public function register(Request $request)
    {
        if (!$request->code) {
            $request->code = '';
        }
        return view('home.register')->with('code', $request->code);
    }


    public function register_make(Request $request)
    {
        $validate = Validator::make($request->all(),
            [
                'phone' => 'required|unique:users|regex:/^1[34578][0-9]{9}$/',
                'captcha' => 'required|captcha_api:' . $request->key,
                'sms_code' => 'required',

            ],
            [
                'phone.required' => '请输入手机号',
                'phone.unique' => '该手机号已注册',
                'phone.regex' => '手机号格式错误',

                'captcha.required' => '请输入图片验证码',
                'captcha.captcha_api' => '图片验证码错误',
                'sms_code.required' => '请输入短信验证码',
            ]
        );

        if ($validate->fails()) {
            return $this->failed($validate->errors()->first());
        }
        $check_sms = $this->checkSmsCode($request->phone, $request->sms_code);
        if ($check_sms !== true) {
            return $this->failed($check_sms['message']);
        }
        $user_code = $request->code; //推荐人code
        
        $p_user = User::where('code', $user_code)->first();
        
        if (!$p_user) {
            $pid = 0;
        }else{
            $pid = $p_user->id;
        }

        $nickname = $this->get_name();
        $code = $this->get_code();

        $data = [
            'phone' => $request->phone,
            'nickname' => $nickname,
            'pid' => $pid,
            'status' => User::STATUS_ABLED,
            'code' => $code,
            'regType' => 1,
        ];
        
        DB::beginTransaction();
        try {
            if($pid){
                Wallet::update_power($p_user->id, 10, 1);
                PowerLog::add_log($p_user->id, 5, 10, 1);
                event(new SendNoticeToOne($p_user,2,6));
            }
            $user_id = User::insertGetId($data);
            event(new UserRegistered($user_id));
            DB::commit();
            return $this->message('注册成功');
        } catch (QueryException $ex) {
            DB::rollback();
            return $this->failed('注册失败');
        }
    }

    //获取昵称
    public function get_name()
    {
        $nickname = '用户' . mt_rand(100000, 999999);
        $user = User::where('nickname', $nickname)->first();

        if ($user) {
            return $this->get_name();
        } else {
            return $nickname;
        }
    }

    //获取邀请码
    public function get_code()
    {
        $code = mt_rand(100000, 999999);
        $user = User::where('code', $code)->first();
        if ($user) {
            return $this->get_code();
        } else {
            return $code;
        }
    }

    public function checkSmsCode($phone, $sms_code)
    {
        $sms = Sms::where(['phone' => $phone, 'code' => $sms_code])->orderBy('id', 'desc')->first();

        if (!$sms) {
            return ['message' => '短信验证码不存在'];
        }
        if ($sms->status == 1) {
            return ['message' => '短信验证码已被使用'];
        }
        if ($sms->expire_time < time()) {
            return ['message' => '短信验证码已过期'];
        }
        if ($sms_code !== $sms->code) {
            return ['message' => '短信验证码错误'];
        }
        $sms->status = 1;
        $sms->save();
        return true;
    }
}
